<template>
  <div class="emergency-notice-node">
    <div class="node-header">
      <h3 class="node-title">险情同步</h3>
      <div class="button-group">
        <el-button type="warning" @click="handleSendNotice" :disabled="!isFormValid">
          发送通知
        </el-button>
        <el-button type="primary" @click="handleNextStep" :disabled="!isFormValid">
          下一步
        </el-button>
      </div>
    </div>

    <!-- 预案信息展示 -->
    <div class="plan-info-section" v-if="selectedPlan">
      <div class="section-title">已选预案信息</div>
      <el-descriptions border :column="2" size="small">
        <el-descriptions-item label="预案名称" :span="2">
          {{ selectedPlan.planName }}
        </el-descriptions-item>
        <el-descriptions-item label="预案类型">
          {{ selectedPlan.planType === 1 ? '总体预案' : '专项预案' }}
        </el-descriptions-item>
        <el-descriptions-item label="事件等级">
          {{ getEventLevelName(selectedPlan.eventLevel) }}
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 通知表单 -->
    <el-form ref="noticeFormRef" :model="noticeForm" :rules="noticeRules" label-width="100px" class="notice-form">
      <el-form-item label="通知标题" prop="title">
        <el-input v-model="noticeForm.title" placeholder="请输入通知标题" maxlength="50" show-word-limit />
      </el-form-item>
      <el-form-item label="通知内容" prop="content">
        <el-input 
          v-model="noticeForm.content" 
          type="textarea" 
          :rows="8" 
          placeholder="请输入通知内容" 
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="通知方式" prop="notifyMethod">
        <el-select v-model="noticeForm.notifyMethod" placeholder="请选择通知方式" style="width: 100%" multiple>
          <el-option
            v-for="option in notifyMethodOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="事件级别" prop="warnLevel">
        <el-select v-model="noticeForm.warnLevel" placeholder="请选择事件级别" style="width: 100%">
          <el-option
            v-for="option in warnLevelOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="通知人员" prop="notifyPersonnel" required style="width: 100%;">
        <el-tree
          ref="deptTreeRef"
          :data="deptOptions"
          :props="{
            label: 'deptName',
            children: 'children'
          }"
          show-checkbox
          node-key="deptId"
          default-expand-all
          :render-content="renderContent"
          @check="handleCheck"
          @check-change="handleCheckChange"
          class="w-full"
        />
        <div v-if="deptOptions.length === 0" class="text-red-500 text-sm mt-1">
          暂无部门数据可选
        </div>
      </el-form-item>
    </el-form>

    <!-- 提示信息 -->
    <div class="tip-section">
      <el-alert
        title="完成险情同步和通知后，点击'下一步'进入现场处置阶段"
        type="success"
        :closable="false"
        show-icon
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, defineEmits, defineProps, nextTick, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import { Folder } from '@element-plus/icons-vue';
import { addNotice, publishNotice } from '@/api/bridge/command/notice';
import { getEmergencyPlanById } from '@/api/bridge/command/emergency';
import { updateEmergencyEvent } from '@/api/bridge/command/event';
import { listDept } from '@/api/system/dept';
import { getUserInfoList } from '@/api/bridge/user/user';
import useUserStore from '@/store/modules/user';
import { listData } from "@/api/system/dict/data";
import type { DictDataQuery } from '@/api/system/dict/data/types';
import { getPlanNoticeRecord } from '@/api/bridge/command/dept';

const props = defineProps({
  eventData: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['next-step']);

// 从localStorage获取选中的预案
const selectedPlan = ref(null);
const deptOptions = ref([]);
const deptTreeRef = ref();

// 通知表单
const noticeFormRef = ref();
interface NoticeFormState {
  title: string;
  content: string;
  warnType: string;
  status: string;
  notifyMethod: string[];
  sendTime: string;
  userId: string;
  eventId: string;
  warnLevel: string;
  notifyPersonnel: string[];
}
const noticeForm = ref<NoticeFormState>({
  title: '应急事件通知',
  content: '',
  warnType: "6", // 应急通知类型
  status: '1',
  notifyMethod: [], // 默认选择短信和邮件
  sendTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  userId: '',
  eventId: '',
  warnLevel: '1', // 默认I级
  notifyPersonnel: []
});

// 表单校验规则
const noticeRules = {
  title: [{ required: true, message: '请输入通知标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入通知内容', trigger: 'blur' }],
  notifyMethod: [{ required: true, message: '请选择通知方式', trigger: 'change' }],
  warnLevel: [{ required: true, message: '请选择事件级别', trigger: 'change' }],
  notifyPersonnel: [{
    validator: (rule, value, callback) => {
      if (!value || value.length === 0) {
        // 手动检查树形控件
        if (deptTreeRef.value) {
          const checkedNodes = deptTreeRef.value.getCheckedNodes();
          if (checkedNodes.length > 0) {
            // 更新字段值
            updateSelectedUsers();
            callback();
            return;
          }
        }
        callback(new Error('请至少选择一个通知对象'));
      } else {
        callback();
      }
    },
    trigger: 'change'
  }]
};

// 通知方式选项
const notifyMethodOptions = ref<any[]>([]);
// 预警级别选项
const warnLevelOptions = ref<any[]>([]);

// 获取通知方式字典
const getNotifyMethodDict = async () => {
  const queryParams: DictDataQuery = {
    dictType: "notification_method",
    pageNum: 1,
    pageSize: 100,
    dictName: "",
    dictLabel: ""
  };
  const res = await listData(queryParams);
  if (res.code === 200) {
    notifyMethodOptions.value = res.rows.map(item => ({
      label: item.dictLabel,
      value: item.dictValue
    }));
  }
};

// 获取预警级别字典
const getWarnLevelDict = async () => {
  const queryParams: DictDataQuery = {
    dictType: "warn_level",
    pageNum: 1,
    pageSize: 100,
    dictName: "",
    dictLabel: ""
  };
  const res = await listData(queryParams);
  if (res.code === 200) {
    warnLevelOptions.value = res.rows.map(item => ({
      label: item.dictLabel,
      value: item.dictValue
    }));
  } else {
    // 如果获取失败，使用默认选项
    warnLevelOptions.value = [
      { label: 'Ⅰ级（特别重大）', value: '1' },
      { label: 'Ⅱ级（重大）', value: '2' },
      { label: 'Ⅲ级（较大）', value: '3' },
      { label: 'Ⅳ级（一般）', value: '4' }
    ];
  }
};

// 判断表单是否有效
const isFormValid = computed(() => {
  return noticeForm.value.title && 
         noticeForm.value.content && 
         noticeForm.value.notifyMethod.length > 0 && 
         noticeForm.value.warnLevel &&
         (noticeForm.value.notifyPersonnel.length > 0 || 
          (deptTreeRef.value && deptTreeRef.value.getCheckedNodes().length > 0));
});

// 获取事件等级名称
const getEventLevelName = (level) => {
  const levels = {
    1: 'Ⅰ级',
    2: 'Ⅱ级',
    3: 'Ⅲ级',
    4: 'Ⅳ级',
    5: '全部'
  };
  return levels[level] || '未知';
};

// 格式化通知内容
const formatNoticeContent = (plan) => {
  if (!plan) return '';
  
  const eventCategories = {
    1: '自然灾害',
    2: '事故灾难',
    3: '公共卫生事件',
    4: '社会安全事件',
    5: '全部'
  };
  
  // 获取当前时间
  const currentTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
  
  // 根据事件和预案信息生成更详细的通知内容
  const content = [
    `【应急事件通知】`,
    ``,
    `发布时间：${currentTime}`,
    ``,
    `预案类型：${plan.planType === 1 ? '总体预案' : '专项预案'}`,
    `预案名称：${plan.planName}`,
    `适用事件类型：${eventCategories[plan.eventCategory] || '未知'}`,
    `适用事件等级：${getEventLevelName(plan.eventLevel)}`,
    `发布单位：${plan.publishUnit}`,
    ``,
    `事件信息：`,
    `发生地点：${props.eventData?.location || '暂无信息'}`,
    `事件描述：${props.eventData?.description || '暂无描述'}`,
    `事件级别：${props.eventData?.eventLevel ? getEventLevelName(props.eventData.eventLevel) : '待定'}`,
    ``,
    `请相关人员按照预案要求，立即开展应急处置工作。各部门人员需做好以下准备：`,
    `1. 按照职责分工，迅速开展应急响应`,
    `2. 做好人员、物资、设备的调度准备`,
    `3. 保持通讯畅通，及时报告现场情况`,
    ``,
    `联系人：${useUserStore().nickname}`,
    `联系电话：暂无`
  ].join('\n');
  
  return content;
};

// 获取部门树状数据
const getDeptTreeData = async () => {
  try {
    // 获取所有部门数据
    const deptRes = await listDept({
      pageNum: 1,
      pageSize: 10000
    });

    // 获取所有用户数据
    const userRes = await getUserInfoList({
      pageNum: 1,
      pageSize: 10000
    });

    if (deptRes.code === 200 && deptRes.data && deptRes.data.length > 0) {
      // 构建用户映射表，按部门ID分组
      const userMap = {};
      if (userRes.code === 200 && userRes.rows) {
        userRes.rows.forEach(user => {
          const deptId = String(user.deptId);
          if (!userMap[deptId]) {
            userMap[deptId] = [];
          }
          userMap[deptId].push({
            userId: user.userId,
            userName: user.userName,
            nickName: user.nickName,
            deptId: deptId,
            deptName: user.deptName
          });
        });
      }

      // 构建树形结构
      const buildDeptTree = (data) => {
        const normalize = data.map(item => ({
          ...item,
          deptId: String(item.deptId),
          parentId: String(item.parentId),
          users: userMap[String(item.deptId)] || []
        }));

        const map = {};
        normalize.forEach(item => {
          map[item.deptId] = { ...item, children: [] };
        });

        const tree = [];
        normalize.forEach(item => {
          const parentId = item.parentId;
          const id = item.deptId;

          if (map[parentId]) {
            map[parentId].children.push(map[id]);
          } else {
            if (parentId === '0') {
              tree.push(map[id]);
            }
          }
        });

        return tree;
      };

      const treeData = buildDeptTree(deptRes.data);
      if (treeData.length === 0 && deptRes.data.length > 0) {
        const { proxy } = getCurrentInstance();
        if (proxy?.handleTree) {
          deptOptions.value = proxy.handleTree(deptRes.data, 'deptId', 'parentId');
        } else {
          deptOptions.value = deptRes.data.map(item => ({
            ...item,
            deptId: String(item.deptId),
            label: item.deptName,
            value: String(item.deptId),
            children: [],
            users: userMap[String(item.deptId)] || []
          }));
        }
      } else {
        deptOptions.value = treeData;
      }
    } else {
      deptOptions.value = [];
    }
  } catch (error) {
    console.error("获取部门数据失败:", error);
    deptOptions.value = [];
  }
};

// 自定义节点渲染
const renderContent = (h, { node, data }) => {
  return h('div', { class: 'custom-tree-node' }, [
    h('span', { class: 'node-label' }, [
      h('span', null, node.label),
      h('span', { class: 'user-count' }, ` (${data.users?.length || 0}人)`)
    ]),
    h('div', { class: 'user-list' },
      data.users?.map(user =>
        h('div', {
          class: 'user-item',
          key: user.userId,
          onClick: (e) => {
            e.stopPropagation();
            handleUserSelect(user, node);
          }
        }, [
          h('el-checkbox', {
            modelValue: isUserSelected(user),
            'onUpdate:modelValue': (val) => handleUserCheck(user, val),
            onClick: (e) => e.stopPropagation()
          }, user.nickName || user.userName)
        ])
      )
    )
  ]);
};

// 处理部门选择
const handleCheck = (data, { checkedKeys, checkedNodes, halfCheckedKeys, halfCheckedNodes }) => {
  updateSelectedUsers();
};

// 处理部门选择状态变化
const handleCheckChange = (data, checked, indeterminate) => {
  updateParentNodeStatus(data);
};

// 处理用户选择
const handleUserSelect = (user, node) => {
  event?.stopPropagation();
};

// 处理用户复选框变化
const handleUserCheck = (user, checked) => {
  const userKey = `${user.deptId}-${user.userId}`;
  if (checked) {
    if (!noticeForm.value.notifyPersonnel.includes(userKey)) {
      noticeForm.value.notifyPersonnel.push(userKey);
    }
  } else {
    noticeForm.value.notifyPersonnel = noticeForm.value.notifyPersonnel.filter(key => key !== userKey);
  }

  updateDeptNodeStatus(user.deptId);
};

// 检查用户是否被选中
const isUserSelected = (user) => {
  const userKey = `${user.deptId}-${user.userId}`;
  return noticeForm.value.notifyPersonnel.includes(userKey);
};

// 更新选中的用户列表
const updateSelectedUsers = () => {
  const tree = deptTreeRef.value;
  if (!tree) return;

  const checkedNodes = tree.getCheckedNodes();
  const halfCheckedNodes = tree.getHalfCheckedNodes();

  const selectedUsers = [];

  checkedNodes.forEach(node => {
    if (node.users) {
      node.users.forEach(user => {
        const userKey = `${user.deptId}-${user.userId}`;
        if (!selectedUsers.includes(userKey)) {
          selectedUsers.push(userKey);
        }
      });
    }
  });

  halfCheckedNodes.forEach(node => {
    if (node.users) {
      node.users.forEach(user => {
        const userKey = `${user.deptId}-${user.userId}`;
        if (isUserSelected(user) && !selectedUsers.includes(userKey)) {
          selectedUsers.push(userKey);
        }
      });
    }
  });

  noticeForm.value.notifyPersonnel = selectedUsers;
};

// 根据部门ID和用户ID查找用户信息
const findUserInfo = (deptId, userId) => {
  const findInDept = (depts) => {
    for (const dept of depts) {
      if (String(dept.deptId) === String(deptId)) {
        const user = dept.users?.find(u => String(u.userId) === String(userId));
        if (user) return user;
      }
      if (dept.children) {
        const found = findInDept(dept.children);
        if (found) return found;
      }
    }
    return null;
  };

  return findInDept(deptOptions.value);
};

// 更新部门节点的选中状态
const updateDeptNodeStatus = (deptId) => {
  const tree = deptTreeRef.value;
  if (!tree) return;
  
  const node = tree.getNode(deptId);
  if (!node) return;
  
  // 获取该部门下所有选中的用户
  const selectedUsers = noticeForm.value.notifyPersonnel.filter(key => 
    key.startsWith(`${deptId}-`)
  );
  
  // 获取该部门下所有用户
  const allUsers = node.data.users || [];
  
  // 更新节点状态
  if (selectedUsers.length === allUsers.length && allUsers.length > 0) {
    tree.setChecked(node, true, false);
  } else if (selectedUsers.length > 0) {
    tree.setChecked(node, false, false);
    node.indeterminate = true;
  } else {
    tree.setChecked(node, false, false);
  }
  
  // 递归更新父节点状态
  updateParentNodeStatus(node.data);
};

// 更新父节点状态
const updateParentNodeStatus = (data) => {
  const tree = deptTreeRef.value;
  if (!tree) return;
  
  const node = tree.getNode(data.deptId);
  if (!node || !node.parent || node.parent.key === 0) return;
  
  const parentNode = node.parent;
  const siblings = parentNode.childNodes;
  
  // 检查所有兄弟节点的状态
  const allChecked = siblings.every(sibling => sibling.checked);
  const someChecked = siblings.some(sibling => sibling.checked || sibling.indeterminate);
  
  if (allChecked) {
    tree.setChecked(parentNode, true, false);
  } else {
    tree.setChecked(parentNode, false, false);
    parentNode.indeterminate = someChecked;
  }
  
  // 递归更新上级节点
  updateParentNodeStatus(parentNode.data);
};

// 处理发送通知
const handleSendNotice = async () => {
  if (!noticeFormRef.value) return;
  
  // 确保notifyPersonnel是最新的选中状态
  updateSelectedUsers();
  
  await noticeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 构建通知记录数据
        const notifyList = [];

        // 处理用户选择(带有 deptId-userId 格式的记录)
        noticeForm.value.notifyPersonnel.forEach(userKey => {
          if (userKey.includes('-')) {
            const [deptId, userId] = userKey.split('-');
            // 从部门树中查找用户信息
            const userInfo = findUserInfo(deptId, userId);
            if (userInfo) {
              notifyList.push({
                departmentId: deptId,
                departmentName: userInfo.deptName,
                personnelId: userId,
                personnelName: userInfo.nickName || userInfo.userName
              });
            }
          }
        });

        // 处理部门选择(所有选中的部门，不带用户ID)
        const checkedDeptNodes = deptTreeRef.value.getCheckedNodes();
        const halfCheckedDeptNodes = deptTreeRef.value.getHalfCheckedNodes();
        const allCheckedDepts = [...checkedDeptNodes, ...halfCheckedDeptNodes];

        allCheckedDepts.forEach(dept => {
          const deptId = String(dept.deptId);
          // 检查该部门是否已经有用户级别的记录
          const hasDeptUserRecord = notifyList.some(record =>
            String(record.departmentId) === deptId && record.personnelId
          );

          // 如果没有用户级别的记录，则添加部门级别的记录
          if (!hasDeptUserRecord) {
            notifyList.push({
              departmentId: deptId,
              departmentName: dept.deptName,
              personnelId: null,
              personnelName: null
            });
          }
        });

        if (notifyList.length === 0) {
          ElMessage.warning('请选择至少一个通知对象');
          return;
        }

        // 准备通知数据
        const noticeData = {
          title: noticeForm.value.title,
          content: noticeForm.value.content,
          warnType: noticeForm.value.warnType,
          status: noticeForm.value.status,
          notifyMethod: Array.isArray(noticeForm.value.notifyMethod) 
            ? noticeForm.value.notifyMethod.join(',') 
            : noticeForm.value.notifyMethod,
          sendTime: noticeForm.value.sendTime,
          userId: noticeForm.value.userId,
          eventId: props.eventData && props.eventData.id 
            ? String(props.eventData.id) 
            : 'temp_' + Date.now(),
          warnLevel: noticeForm.value.warnLevel,
          notifyList: notifyList
        };

        // 发送通知
        const res = await addNotice(noticeData);
        if (res.code === 200) {
          await publishNotice(res.data);
          ElMessage.success('通知已发送');
        } else {
          ElMessage.error(res.msg || '发送通知失败');
        }
      } catch (error) {
        console.error('发送通知失败:', error);
        ElMessage.error('发送通知失败');
      }
    }
  });
};

// 处理下一步
const handleNextStep = async () => {
  if (!noticeFormRef.value) return;
  
  // 确保notifyPersonnel是最新的选中状态
  updateSelectedUsers();
  
  await noticeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 直接触发next-step事件，不在此更新事件状态
        // 避免与flowLog.vue中的goToNextNode重复调用更新接口
        ElMessage.success('进入现场处置阶段');
        emit('next-step');
      } catch (error) {
        console.error('进入下一步失败:', error);
        ElMessage.error('操作失败');
      }
    }
  });
};

// 从预案ID获取预案信息
const fetchPlanDetails = async () => {
  try {
    if (props.eventData && props.eventData.planId) {
      const res = await getEmergencyPlanById(props.eventData.planId);
      if (res.code === 200) {
        selectedPlan.value = res.data;
        noticeForm.value.content = formatNoticeContent(selectedPlan.value);
        localStorage.setItem('selectedPlan', JSON.stringify(selectedPlan.value));
        
        // 不在这里直接调用 getPlanNoticeRecords
        return res.data.id; // 返回预案ID以便后续使用
      } else {
        ElMessage.warning('获取预案信息失败');
      }
    } else {
      // 尝试从localStorage获取
      const planJson = localStorage.getItem('selectedPlan');
      const planId = localStorage.getItem('selectedPlanId');
      
      if (planJson) {
        selectedPlan.value = JSON.parse(planJson);
        noticeForm.value.content = formatNoticeContent(selectedPlan.value);
        
        // 不在这里直接调用 getPlanNoticeRecords
        return planId; // 返回预案ID以便后续使用
      } else {
        ElMessage.warning('未找到预案信息，请返回上一步选择预案');
      }
    }
    
    return null;
  } catch (error) {
    console.error('获取预案详情失败:', error);
    ElMessage.error('获取预案详情失败');
    return null;
  }
};

// 获取预案通知记录
const getPlanNoticeRecords = async (planId) => {
  try {
    const res = await getPlanNoticeRecord({ planId });
    if (res.code === 200 && res.rows) {
      // 将通知记录转换为前端需要的格式
      const selectedPersonnel = res.rows.map(record => {
        if (record.personnelId) {
          // 如果有用户ID，使用 deptId-userId 格式
          return `${record.departmentId}-${record.personnelId}`;
        } else {
          // 如果只有部门ID，只返回部门ID
          return String(record.departmentId);
        }
      }).filter(Boolean);
      
      // 更新表单中的选中人员
      noticeForm.value.notifyPersonnel = selectedPersonnel;

      // 在树形控件中设置选中状态
      const setTreeSelections = () => {
        if (!deptTreeRef.value) {
          console.warn('树组件未初始化，300ms后重试');
          setTimeout(setTreeSelections, 300);
          return;
        }
        
        // 先重置所有选中状态
        deptTreeRef.value.setCheckedKeys([]);
        
        // 处理部门的选中状态
        const deptIds = new Set(res.rows
          .map(record => String(record.departmentId))
          .filter(Boolean));
        
        // 设置部门的选中状态
        deptIds.forEach(deptId => {
          const node = deptTreeRef.value.getNode(deptId);
          if (node) {
            deptTreeRef.value.setChecked(node.key, true, false);
          }
        });

        // 处理用户的选中状态
        selectedPersonnel.forEach(key => {
          if (key.includes('-')) {
            const [deptId] = key.split('-');
            updateDeptNodeStatus(deptId);
          }
        });
      };
      
      // 启动设置流程
      setTimeout(setTreeSelections, 300);
    } else {
      noticeForm.value.notifyPersonnel = [];
    }
  } catch (error) {
    console.error("获取预案通知记录失败:", error);
    noticeForm.value.notifyPersonnel = [];
  }
};

onMounted(async () => {
  try {
    // 获取用户信息
    const userStore = useUserStore();
    if (userStore.userId) {
      noticeForm.value.userId = String(userStore.userId); // 确保userId是字符串类型
    }
    
    // 先获取选中的预案基本信息（不包含通知人员）
    const planId = await fetchPlanDetails();
    
    // 先获取部门和用户数据
    await getDeptTreeData();
    
    // 获取通知方式字典和预警级别字典
    await getNotifyMethodDict();
    await getWarnLevelDict();
    
    // 确保部门树已经渲染完成后，再获取并设置通知人员
    if (planId) {
      // 使用更长的延迟，确保DOM完全渲染
      setTimeout(async () => {
        // 等待DOM渲染和树组件初始化完成
        if (deptTreeRef.value) {
          await getPlanNoticeRecords(planId);
        } else {
          // 如果树组件还未初始化，再次延迟尝试
          setTimeout(async () => {
            await getPlanNoticeRecords(planId);
          }, 300);
        }
      }, 300);
    }
  } catch (error) {
    console.error('初始化数据失败:', error);
  }
});
</script>

<style scoped lang="scss">
.emergency-notice-node {
  padding: 20px;
  
  .node-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .node-title {
      font-size: 18px;
      font-weight: 600;
      margin: 0;
      color: var(--el-text-color-primary);
    }
    
    .button-group {
      display: flex;
      gap: 10px;
    }
  }
  
  .plan-info-section {
    margin-bottom: 20px;
    padding: 16px;
    border: 1px solid var(--el-border-color-light);
    border-radius: 8px;
    background-color: var(--el-fill-color-light);
    
    .section-title {
      font-weight: 600;
      margin-bottom: 16px;
      color: var(--el-text-color-primary);
    }
  }
  
  .notice-form {
    margin-bottom: 20px;
  }
  
  .tip-section {
    margin-top: 20px;
  }
  
  // 部门树样式
  :deep(.el-tree) {
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid var(--el-border-color-light);
    border-radius: 4px;
    padding: 8px;
    
    .el-tree-node__content {
      height: 32px;
    }
  }
  
  .w-full {
    width: 100%;
  }
  
  // 自定义树节点样式
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    font-size: 14px;
    padding-right: 8px;
    flex-direction: column;
    align-items: flex-start;
  }

  .node-label {
    display: flex;
    align-items: center;
    gap: 8px;
    width: 100%;
  }

  .user-count {
    color: #909399;
    font-size: 12px;
  }

  .user-list {
    margin-left: 24px;
    padding: 4px 0;
    width: 100%;
  }

  .user-item {
    display: flex;
    align-items: center;
    padding: 2px 0;
    cursor: pointer;
  }

  .user-item:hover {
    background-color: var(--el-fill-color-light);
  }
}
</style> 